package com.xzz.mq.consumer;

import com.alibaba.fastjson.JSON;
import com.xzz.domain.CourseOrder;
import com.xzz.domain.PayOrder;
import com.xzz.dto.PayResultDto;
import com.xzz.service.ICourseOrderService;
import io.netty.util.CharsetUtil;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@RocketMQMessageListener(
        consumerGroup = "service-order-consumer",
        topic="topic-pay",
        selectorExpression="tag-pay",
        messageModel= MessageModel.BROADCASTING   //广播模式： 一个消息可以被多个人同时消费
)
public class OrderConsumer implements RocketMQListener<MessageExt> {

    @Autowired
    private ICourseOrderService courseOrderService;

    @Override
    public void onMessage(MessageExt message) {
        String msg = new String(message.getBody(), CharsetUtil.UTF_8);
        PayResultDto payResultDto = JSON.parseObject(msg, PayResultDto.class);

        CourseOrder courseOrder = courseOrderService.selectByOrderNo(payResultDto.getOrderNo());
        //如果订单不存在，说明有人破坏，幂等性，这是消费者的报错方式
        if (courseOrder == null){
            return;
        }
        if(courseOrder.getStatusOrder() != CourseOrder.STATE_WAITE_PAY){
            return;//订单不是待支付状态
        }
        //更新订单的状态以及修改时间
        courseOrderService.updateCourseOrder(payResultDto);
    }
}